<template>
  <view>
    <view class="login-container">
      <!-- 提示登录的图标 -->
      <uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
      <!-- 登录按钮 -->
      <button 
        type="primary" 
        class="btn-login" 
        @getuserinfo="getuserinfo" 
        open-type="getUserInfo"
      >一键登录</button>
      <!-- 登录提示 -->
      <view class="tips-text">登录后尽享更多权益</view>
    </view>
  </view>
</template>

<script>
  import { mapMutations, mapState } from 'vuex'
export default {
  name: 'my-login',
  computed: {
    ...mapState('m_user', ['jumpInfo'])
  },
  data() {
    return {}
  },
  methods: {
    ...mapMutations('m_user', ['updateUserInfo', 'updateToken', 'updateJumpInfo']),
    getuserinfo(e) {
      // console.log(e)
      // console.log(e.detail.userInfo)
      this.updateUserInfo(e.detail.userInfo)
      
      // 登录并获取 token
      this.getToken(e.detail)
    },
    
    async getToken(res) {
      const [err, succ] = await uni.login()
      if (err !== null || succ.errMsg !== 'login:ok' ) {
        return uni.$showError('登陆失败, 请重新登录')
      }
      
      const query = {
        encryptedData: res.encryptedData,
        rawData: res.rawData,
        iv: res.iv,
        signature: res.signature,
        code: succ.code
      }
      
      const data = await uni.$http.post('/api/public/v1/users/wxlogin', query)
      // console.log(data)
      // if (data.meta.status !== 200) return uni.$showMsg('登陆失败, 请重新登录')
      // this.updateUserInfo(data.message.token)
      const tokenStr = 'Bearer eyJhbGciOiJIUzI1NiIBearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjE2OSwiaWF0IjoxNjYzNzQzMTg5LCJleHAiOjEwMDE2NjM3NDMxODh9.JMxT8SIytaIAFyh73-M7ev2FrbFR2KZ6gUw5wCdL7N4"sInR5cCI6IkpXVCJ9.eyJ1aWQiOjE2OSwiaWF0IjoxNjYzNzQzMTg5LCJleHAiOjEwMDE2NjM3NDMxODh9.JMxT8SIytaIAFyh73-M7ev2FrbFR2KZ6gUw5wCdL7N4'
      this.updateToken(tokenStr)
      
      // 登录成功后返回登录之前的页面
      if (this.jumpInfo && this.jumpInfo.opentype === 'switchTab') {
        uni.switchTab({
          url: this.jumpInfo.from,
          
          // 跳回购物车页面后清空购物车持久化信心
          complete: () => {
            this.updateJumpInfo({})
          }
        })
      }
    }
  }
};
</script>

<style lang="scss">
.login-container {
  // 登录盒子的样式
  height: 750rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;

  // 登录按钮的样式
  .btn-login {
    width: 90%;
    border-radius: 100px;
    margin: 15px 0;
    background-color: #c00000;
  }

  // 按钮下方提示消息的样式
  .tips-text {
    font-size: 12px;
    color: gray;
  }
}
</style>
